package com.plian.system.service.pm.listedcompany.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pm.listedcompany.MattersRecord;
import com.plian.system.mapper.pm.listedcompany.MattersRecordMapper;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.service.pm.listedcompany.IMattersRecordService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.listedcompany.MattersRecordVO;
import com.plian.system.wrapper.pm.listedcompany.MattersRecordWrapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Description: TODO
 * @Author: Take-off
 * @Date: 2023/2/27 9:30 AM
 * @Param
 * @return
 * @Version: 1.0
 **/
@Service
@AllArgsConstructor
public class MattersRecordServiceImpl extends BaseServiceImpl<MattersRecordMapper,MattersRecord> implements IMattersRecordService, BaseFlowService {

    private final FormWorkflowService formWorkflowService;

    private final IFormCodeService formCodeService;

    private final MattersRecordWrapper mattersRecordWrapper;

    private final FileService fileService;

    @Override
    public boolean saveOrUpdate(MattersRecord mattersRecord) {
        boolean flag = false;
        if (!Optional.ofNullable(mattersRecord.getStatus()).isPresent()) {
            mattersRecord.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (mattersRecord.getStatus().equals(FormStatusConstant.REJECT)) {
            mattersRecord.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (!Optional.ofNullable(mattersRecord.getId()).isPresent()) {
            flag = true;
            mattersRecord.setCode(formCodeService.getCode(FormTypeConstant.QM_COMPREHENSIVE_MATTERS));
            mattersRecord.setFormType(String.valueOf(FormTypeConstant.QM_COMPREHENSIVE_MATTERS));
        }
        boolean result = super.saveOrUpdate(mattersRecord);
        if (flag){
            fileService.saveAll(String.valueOf(mattersRecord.getId()), mattersRecord.getDocList());
        }else {
            fileService.edit(String.valueOf(mattersRecord.getId()), mattersRecord.getDocList());
        }

        return result;
    }

    @Override
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            MattersRecord mattersRecord = getById(id);
            if (mattersRecord == null) {
                return false;
            } else if (mattersRecord.getStatus() != null &&
                    (mattersRecord.getStatus() != FormStatusConstant.STASH && mattersRecord.getStatus() != FormStatusConstant.UNREVIEWED)) {
                return false;
            }
            formWorkflowService.deleteProcessInstance(String.valueOf(id));
        }
        return super.deleteLogic(ids);
    }

    @Override
    public MattersRecordVO getDetailObj(MattersRecord mattersRecord) {
        MattersRecord detail = getOne(Condition.getQueryWrapper(mattersRecord));
        MattersRecordVO mattersRecordVO = mattersRecordWrapper.entityToVO(detail);
        return mattersRecordVO;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState,String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<MattersRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(MattersRecord::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<MattersRecord> mattersRecords = list(queryWrapper);
        List<MattersRecordVO> mattersRecordVOS = mattersRecordWrapper.entityToVO(mattersRecords);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(mattersRecordVOS)){
                for (MattersRecordVO vo : mattersRecordVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getFillingOrgName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getCreateCompanyId());
                    pd.put("formType", FormTypeConstant.QM_COMPREHENSIVE_MATTERS);
                    pd.put("orgName", vo.getFillingOrgName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.QM_COMPREHENSIVE_MATTERS);
    }

    @Override
    public void goBackToStash(String formId) {
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    /**
     * 统一处理状态机事件方法
     *
     * @param id          主键
     * @param updateStatus  更新状态
     * @return boolean
     */
    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            MattersRecord mattersRecord = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                mattersRecord.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                mattersRecord.setApprovedTime(now);
            }
            mattersRecord.setStatus(updateStatus);
            updateById(mattersRecord);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }
}
